package com.personal.dao.sqlgenerator;

import java.util.ArrayList;
import java.util.List;

import com.personal.dao.bean.BaseModel;
import com.personal.dao.configuration.Configuration;
import com.personal.dao.exception.NoPrimaryKeyException;
import com.personal.dao.metadata.DataBaseFieldMetadata;
import com.personal.dao.metadata.DataBaseTableMetadata;
import com.personal.dao.reflection.MetaObject;
import com.personal.dao.sql.BaseBatchSql;

/**
 * 批量插入
 * @author cuibo
 *
 */
public class BatchUpdate<T extends BaseModel> extends BaseBatchSqlGenerator<T>
{

    public BatchUpdate(List<T> records, DataBaseTableMetadata<T> metadata)
    {
        super(records, metadata);
    }

    @Override
    public BaseBatchSql generate()
    {
        // 次操作需要校验主键
        checkPrimaryKey();
        StringBuilder sql = new StringBuilder("update ").append(metadata.getTableName());
        sql.append(" set ");
        // 生成元Object
        int index = -1;
        List<Object[]> datas = new ArrayList<>(records.size());
        for (T record : records)
        {
        	MetaObject metaObject = Configuration.getInstance().newMetaObject(record);
        	// 校验
        	SqlValidator.validate(metadata, record, metaObject);
            index ++;
            Object[] data = new Object[metadata.getFields().size() + 1];
            int colIndex = 0;
            for (DataBaseFieldMetadata field : metadata.getFields())
            {
                Object value = metaObject.getValue(field.getFieldName());
                data[colIndex ++] = value;
                if (index == 0)
                {
                    sql.append(field.getColumnName()).append(" = ?,");
                }
            }
            // 所有的data都加上主键
            Object pk = metaObject.getValue(metadata.getPrimaryKey().getFieldName());
            if (pk == null)
            {
                throw new NoPrimaryKeyException(record + "的主键为空！");
            }
            data[data.length - 1] = pk;
            datas.add(data);
        }
        // 如果值不为空，则截取最后的,
        sql.deleteCharAt(sql.length() - 1);
        sql.append(" where ").append(metadata.getPrimaryKey().getColumnName()).append(" = ?");
        return new BaseBatchSql(sql.toString(), datas);
    }

}
